package org.anachronos.jeep.ui.trace;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;

public class TraceViewerSorter extends ViewerSorter {
	private TraceColumnSwitch comparableSwitch = new TraceColumnSwitch();

	private int sortDirection;

	public void setSortColumnIndex(final int index) {
		comparableSwitch.setColumnIndex(index);
	}
	
	public void setSortDirection(final int sortDirection) {
		this.sortDirection = sortDirection;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public int compare(final Viewer viewer, final Object e1, final Object e2) {
		if (!(e1 instanceof EObject)) {
			return -1;
		} else if (!(e2 instanceof EObject)) {
			return 1;
		}
		final EObject eObject1 = (EObject) e1;
		final Comparable<Object> comparable1 = (Comparable<Object>) 
			comparableSwitch.doSwitch(eObject1);
		final EObject eObject2 = (EObject) e2;
		final Comparable<Object> comparable2 = (Comparable<Object>) 
			comparableSwitch.doSwitch(eObject2);
		final int sign = sortDirection == SWT.UP ? -1 : 1;
		return sign * comparable1.compareTo(comparable2);
	}
}
